<template>
  <div class="follow-up-dialog">
    <el-dialog v-model="isFollowUp" width="510" :align-center="true" :show-close="false" :close-on-click-modal="false">
      <template #header>
        <title-view title="客户跟进"></title-view>
      </template>
      <el-form
        ref="followUpFormRef"
        v-if="isFollowUp"
        :model="followUpForm"
        :rules="followUpRules"
        label-width="110px"
        status-icon
      >
        <el-form-item label="跟进类型" prop="trackType">
          <el-select v-model="followUpForm.trackType">
            <el-option v-for="item in followUpTypes" :key="item.dictCode" :label="item.dictLabel" :value="item.dictCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进时间" prop="trackDatetime">
          <el-input disabled v-model="followUpForm.trackDatetime"></el-input>
        </el-form-item>
        <el-form-item label="跟进内容" prop="contentDesc">
          <el-input
            v-model="followUpForm.contentDesc"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            show-word-limit
            :maxlength="200"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <ali-oss-upload
            :folder="defaultConfig.fileFolder"
            :fileList="upImagesList"
            :maxSize="10"
            :maxLength="8"
            file-tip="注：最多可上传8张，单张不超过10M，支持JPG/JPEG/PNG格式"
            :accept="accept"
            multiple
            list-type="picture-card"
            @uploadSuccess="uploadSuccess"
            @removeFile="removeFile"
          ></ali-oss-upload>
        </el-form-item>
        <el-form-item label="下次跟进设置">
          <el-switch v-model="followUpForm.isNextSetting" @change="changeNextSetting"></el-switch>
        </el-form-item>
        <template v-if="followUpForm.isNextSetting">
          <el-form-item label="下次跟进时间" :rules="{ required: true, message: '请选择下次跟进时间', trigger: 'change' }">
            <el-date-picker
              @change="changeNextDateTine"
              v-model="followUpForm.nextDateTine"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD"
              time-format="HH:mm:ss"
              :disabled-date="datePicker.disabledDate"
              :disabled-hours="datePicker.disabledHour"
              :disabled-minutes="datePicker.disabledMinute"
              :disabled-seconds="datePicker.disabledSecond"
            />
          </el-form-item>
          <el-form-item label="提醒时间">
            <el-date-picker
              v-model="followUpForm.nextTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD"
              time-format="HH:mm:ss"
              :disabled-date="datePicker.disabledDate"
              :disabled-hours="datePicker.disabledHour"
              :disabled-minutes="datePicker.disabledMinute"
              :disabled-seconds="datePicker.disabledSecond"
            />
          </el-form-item>
          <el-form-item label="提醒内容">
            <el-input
              v-model="followUpForm.nextContent"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              show-word-limit
              :maxlength="200"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="跟进任务"
            prop="stageTaskId"
            :rules="{ required: true, message: '请选择跟进任务', trigger: 'change' }"
          >
            <el-select v-model="followUpForm.stageTaskId">
              <el-option v-for="item in followOptions" :key="item.stageTaskId" :label="item.taskName" :value="item.stageTaskId" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="closeFollowUp" size="large">取消</el-button>
          <el-button style="width: 92px" type="primary" @click="handelFollowUpSubmit" size="large">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, nextTick, ref, getCurrentInstance } from "vue";
import { dayjs } from "element-plus";
import defaultConfig from "@/settings";
import { initFollowUpForm } from "./config";
import * as datePicker from "@/utils/disabledOldDate";
import { dictList } from "@/apis/dict/dict";
import { followTaskList } from "@/apis/myClient";
import { addTrack } from "@/apis/clientManager";

const { proxy } = getCurrentInstance();

const props = defineProps({
  modelValue: Boolean,
  taskInfo: {
    type: Object,
    default: () => ({})
  }
});
const emits = defineEmits(["update:modelValue", "submitAfter", "cancel"]);
const isFollowUp = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  }
});

const followUpForm = ref({
  ...initFollowUpForm
});
const followUpRules = {
  trackType: { required: true, message: "跟进类型不能为空", trigger: "change" },
  trackDatetime: { required: true, message: "跟进时间不能为空", trigger: "blur" },
  contentDesc: { required: true, message: "跟进内容不能为空", trigger: "blur" }
};

/**
 * 跟进类型
 */
const followUpTypes = ref([]);
const getFollowUpType = async () => {
  try {
    const { data } = await dictList({ dictType: defaultConfig.dicts.FOLLER_UP_TYPE });
    followUpTypes.value = data ?? [];
  } catch (err) {
    console.log(err);
  }
};

/**
 * 跟进图片
 */
const upImagesList = ref([]);
const accept = ".jpg,.JPG,.jpeg,.JPEG,.png,.PNG";
const uploadSuccess = data => {
  upImagesList.value.push({ fileUrl: data.fileUrl });
};
const removeFile = file => {
  upImagesList.value.splice(file.index, 1);
};

/**
 * 任务列表
 */
const followOptions = ref([]);
const getFollowList = async () => {
  try {
    const customerId = props.taskInfo.customerId;
    const { data } = await followTaskList(customerId);
    followOptions.value = data ?? [];
  } catch (err) {
    console.log(err);
  }
};

/**
 * 下次跟进
 */
const changeNextSetting = data => {
  if (data) {
    followUpForm.value.nextDateTine = dayjs().format("YYYY-MM-DD HH:mm:ss");
    followUpForm.value.nextTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    getFollowList();
  }
};
const changeNextDateTine = e => {
  followUpForm.value.nextTime = dayjs(e).format("YYYY-MM-DD HH:mm:ss");
};

/**
 * 提交跟进
 */
const handelSubmitData = () => {
  followUpForm.value.customerId = props.taskInfo.customerId;
  followUpForm.value.crmFileCreateVOList =
    upImagesList.value?.map(item => {
      return {
        url: item.fileUrl
      };
    }) || [];
  followUpForm.value.nextDateTine = dayjs(followUpForm.value.nextDateTine).format("YYYY-MM-DD HH:mm:ss");
  followUpForm.value.isNextSetting = followUpForm.value.isNextSetting ? 1 : 0;
  followUpForm.value.commTaskId = props.taskInfo.commTaskId;
  followUpForm.value.stageTaskId = followUpForm.value.isNextSetting ? followUpForm.value.stageTaskId : "";
};
const handelFollowUpSubmit = () => {
  proxy.$refs.followUpFormRef.validate(async valid => {
    if (!valid) {
      return proxy.$modal.msgError("请完善信息");
    }
    try {
      handelSubmitData();
      await addTrack(followUpForm.value);
      emits("submitAfter");
      closeFollowUp();
    } catch (err) {
      console.log(err);
    }
  });
};
const closeFollowUp = async () => {
  await nextTick();
  proxy.$refs.followUpFormRef.resetFields();
  upImagesList.value = [];
  followUpForm.value = {
    ...initFollowUpForm
  };
  isFollowUp.value = false;
};

/**
 * 初始化数据
 */
const getNowDate = () => dayjs().format("YYYY-MM-DD HH:mm:ss");
const nowData = getNowDate();
const initFollowData = () => {
  getFollowUpType();
  followUpForm.value = {
    ...initFollowUpForm,
    trackDatetime: nowData,
    nextDateTine: nowData,
    nextTime: nowData
  };
};

initFollowData();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
.follow-up-dialog {
  :deep(.el-dialog) {
    @include mixin.flex-column;
    max-height: 80vh;
    overflow-y: hidden;
  }
  :deep(.el-dialog__header) {
    margin-bottom: 24px;
  }
  :deep(.el-dialog__body) {
    @include mixin.flex-overflow;
  }
  :deep(.el-date-editor) {
    width: 100% !important;
  }
  .dialog-footer {
    text-align: center;
  }
}
</style>
